package com.zhuiyun.project.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zhuiyun.project.api.wxlogin.config.WeiXinAuth;
import org.apache.commons.lang3.StringUtils;

/**
 * @ClassName WXUtils
 * @Description TODO
 * @Author kdj
 * @Date 2023/6/19 14:51
 **/
public class WXUtils {

    /**
     * @Description 获取openid
     * @Author HH
     * @Date 2023/4/11 8:28
     * @Return java.lang.String
     */
    public static JSONObject getOpenid(String code) {
        // 请求获取openid路径
        String code2Session = "https://api.weixin.qq.com/sns/jscode2session?appid=" + WeiXinAuth.WEIXIN_APPID +
                "&secret=" + WeiXinAuth.WEIXIN_APPSECRET + "&js_code=" + code + "&grant_type=authorization_code";
        String resultString = HttpUtils.methodGet(code2Session);
        return JSON.parseObject(resultString);
    }
    /**
     * @param
     * @Author kdj
     * @Description 获取AccessToken（微信快捷登录）
     * @Date 2023/6/17 16:47
     * @Return java.lang.String
     */
    public static String getAccessToken() {
        String accessToken = "";
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + WeiXinAuth.WEIXIN_APPID + "&secret=" + WeiXinAuth.WEIXIN_APPSECRET;
        try {
            String resultString = HttpUtils.methodGet(url);
            if (StringUtils.isNotEmpty(resultString)) {
                JSONObject jsonObject = JSON.parseObject(resultString);
                accessToken = jsonObject.get("access_token").toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return accessToken;
    }

    /**
     * @param code
     * @Author kdj
     * @Description 根据 vx信息获取用户绑定微信手机号
     * @Date 2023/6/17 18:29
     * @Return java.lang.String
     */
    public static String getPhoneNumber(String code) {
        String phoneNumber = "";
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + getAccessToken();
        JSONObject obj = new JSONObject();
        //小程序发来的code
        obj.put("code", code);
        try {
            String resultString = HttpUtils.methodPost(url, obj.toString());
            if (StringUtils.isNotEmpty(resultString)) {
                JSONObject jsonObject = JSON.parseObject(resultString);
                JSONObject phone_info = jsonObject.getJSONObject("phone_info");
                phoneNumber = phone_info.getString("phoneNumber");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return phoneNumber;
    }

}
